package com.tql.test_02;

public class PCTest {
    public static void main(String[] args) {
        PCTest1 pcTest1=new PCTest1();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest1.increment(); },"A").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest1.decrment(); },"B").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest1.increment(); },"C").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest1.decrment(); },"D").start();
    }
}
//资源类，降低耦合，线程处理资源类
//生产者消费者问题 六字核心  判断等待 业务  通知唤醒
class PCTest1{
    int num=0;
    //生产 +1
    public  synchronized void increment()  {
        while(num!=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"执行了加操作 "+num);
        this.notifyAll();
    }
    //消费 -1
    public  synchronized void decrment()  {
        while(num==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"执行了减操作 "+num);
        this.notifyAll();
    }

}